package org.example.datascreen.service.Impl;

import okhttp3.*;
import org.example.datascreen.configuration.FboxConfig;
import org.example.datascreen.configuration.YingshiConfig;
import org.example.datascreen.service.TokenService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private FboxConfig fboxConfig;
        
    @Override
    public String getfboxToken() {
        OkHttpClient client = new OkHttpClient();
        
        // 构建token请求体
        FormBody formBody = new FormBody.Builder()
            .add("grant_type", fboxConfig.getGrantType())
            .add("scope", fboxConfig.getScope())
            .add("client_id", fboxConfig.getClientId())
            .add("client_secret", fboxConfig.getClientSecret())
            .build();

        Request request = new Request.Builder()
            .url(fboxConfig.getLoginUrl())
            .post(formBody)
            .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("获取token失败: " + response);
            }
            JSONObject jsonResponse = new JSONObject(response.body().string());
            return jsonResponse.getString("access_token");
        } catch (IOException e) {
            throw new RuntimeException("获取token失败", e);
        }
    }
    @Autowired
    private YingshiConfig yingshiConfig;
    
    @Override
    public String getyingshiToken() {
        OkHttpClient client = new OkHttpClient();
        
        // 构建JSON格式的请求体
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(
            String.format("{\r\n    \"accountId\": \"%s\"\r\n}", yingshiConfig.getAccountId()),
            mediaType
        );

        Request request = new Request.Builder()
            .url(yingshiConfig.getLoginUrl())
            .post(requestBody)
            .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("获取token失败: " + response);
            }
            JSONObject jsonResponse = new JSONObject(response.body().string());
            return jsonResponse.getJSONObject("data").getString("accessToken");
        } catch (IOException e) {
            throw new RuntimeException("获取token失败", e);
        }
    }


}
